using ComponentSystem;
using UnityEngine;
using ZYFramework.ObjectPool;

namespace ZYFramework.AudioSystem
{
    /// <summary>
    /// AudioSource对象池组件
    /// </summary>
    public class Com_AudioSourcePool : ComponentWithId
    {
        private PoolManager_Entity _poolManager => PoolManager_Entity._instance;

        /// <summary>
        /// 2D AudioSource对象池
        /// </summary>
        private Com_ObjectPool<GameObject> _pool2D;

        /// <summary>
        /// 3D AudioSource对象池
        /// </summary>
        private Com_ObjectPool<GameObject> _pool3D;

        /// <summary>
        /// 2D音效根节点（用于管理2D AudioSource）
        /// </summary>
        private Transform _pool2DRoot;

        /// <summary>
        /// 3D音效根节点（用于管理3D AudioSource的位置）
        /// </summary>
        private Transform _pool3DRoot;

        /// <summary>
        /// 框架配置
        /// </summary>
        private AudioConfig _config;

        protected override void Awake()
        {
            base.Awake();
        }

        protected override void Start()
        {
            base.Start();
        }

        /// <summary>
        /// 初始化对象池
        /// </summary>
        /// <param name="config">框架配置</param>
        public void Initialize(AudioConfig config)
        {
            this._config = config;

            // 创建2D音效根节点
            GameObject pool2DRootObj = new GameObject(_config.Audio2DRootName);
            UnityEngine.Object.DontDestroyOnLoad(pool2DRootObj);
            _pool2DRoot = pool2DRootObj.transform;

            // 创建3D音效根节点
            GameObject pool3DRootObj = new GameObject(_config.Audio3DRootName);
            UnityEngine.Object.DontDestroyOnLoad(pool3DRootObj);
            _pool3DRoot = pool3DRootObj.transform;

            // 初始化2D对象池
            InitPool2D();

            // 初始化3D对象池
            InitPool3D();
        }

        /// <summary>
        /// 初始化2D对象池
        /// </summary>
        private void InitPool2D()
        {
            var config2D = new ObjectPoolConfig<GameObject>
            {
                MaxCapacity = _config.PoolMaxSize_2D,
                MinCapacity = 0,
                EnableAutoRecycle = false,
                CreationFunc_Sync = () => CreateAudioSourceGameObject(false), // 2D音效
                ActivationFunc_Sync = (obj) => { obj.SetActive(true); },
                RecycleFunc_Sync = (obj) => { ResetAudioSource(obj); obj.SetActive(false); },
                //预热5个
                PrewarmCount = 5,
            };

            _pool2D = (Com_ObjectPool<GameObject>)_poolManager.RegisterPool<GameObject>("AudioSource2D", config2D); ;
        }

        /// <summary>
        /// 初始化3D对象池
        /// </summary>
        private void InitPool3D()
        {
            var config3D = new ObjectPoolConfig<GameObject>
            {
                MaxCapacity = _config.PoolMaxSize_3D,
                MinCapacity = 0,
                CreationFunc_Sync = () => CreateAudioSourceGameObject(true), // 3D音效
                ActivationFunc_Sync = (obj) => { obj.SetActive(true); },
                RecycleFunc_Sync = (obj) => { ResetAudioSource(obj); obj.SetActive(false); },
                //预热5个
                PrewarmCount = 5,
            };

            _pool3D = (Com_ObjectPool<GameObject>)_poolManager.RegisterPool<GameObject>("AudioSource3D", config3D);
        }

        /// <summary>
        /// 创建带AudioSource的GameObject
        /// </summary>
        /// <param name="is3D">是否为3D音效</param>
        /// <returns>GameObject</returns>
        private GameObject CreateAudioSourceGameObject(bool is3D)
        {
            GameObject go = new GameObject($"AudioSource_{(is3D ? "3D" : "2D")}");
            AudioSource audioSource = go.AddComponent<AudioSource>();

            // 配置AudioSource
            audioSource.playOnAwake = false;
            audioSource.spatialBlend = is3D ? 1f : 0f; // 0=2D, 1=3D

            return go;
        }

        /// <summary>
        /// 重置AudioSource属性
        /// </summary>
        /// <param name="obj">GameObject</param>
        private void ResetAudioSource(GameObject obj)
        {
            if (obj == null) return;

            AudioSource audioSource = obj.GetComponent<AudioSource>();
            if (audioSource != null)
            {
                audioSource.Stop();
                audioSource.clip = null;
                audioSource.volume = 1f;
                audioSource.pitch = 1f;
                audioSource.loop = false;
                audioSource.time = 0f;
            }
        }

        /// <summary>
        /// 获取空闲的2D AudioSource
        /// </summary>
        /// <param name="priority">优先级</param>
        /// <returns>GameObject（带AudioSource）</returns>
        public GameObject GetFreeAudioSource2D()
        {
            if (_pool2D == null)
            {
                Debug.LogError("[AudioSourcePool] 2D对象池未初始化");
                return null;
            }

            return _pool2D.Get_Sync();
        }

        /// <summary>
        /// 获取空闲的3D AudioSource
        /// </summary>
        /// <param name="priority">优先级</param>
        /// <returns>GameObject（带AudioSource）</returns>
        public GameObject GetFreeAudioSource3D()
        {
            if (_pool3D == null)
            {
                Debug.LogError("[AudioSourcePool] 3D对象池未初始化");
                return null;
            }

            return _pool3D.Get_Sync();
        }

        /// <summary>
        /// 回收AudioSource到2D池
        /// </summary>
        /// <param name="audioSource">AudioSource对应的GameObject</param>
        public void RecycleAudioSource2D(GameObject audioSource)
        {
            if (_pool2D == null || audioSource == null)
            {
                return;
            }

            _pool2D.Release_Sync(audioSource);
        }

        /// <summary>
        /// 回收AudioSource到3D池
        /// </summary>
        /// <param name="audioSource">AudioSource对应的GameObject</param>
        public void RecycleAudioSource3D(GameObject audioSource)
        {
            if (_pool3D == null || audioSource == null)
            {
                return;
            }

            _pool3D.Release_Sync(audioSource);
        }

        /// <summary>
        /// 获取3D音效根节点
        /// </summary>
        /// <returns>Transform</returns>
        public Transform GetPool3DRoot()
        {
            return _pool3DRoot;
        }

        /// <summary>
        /// 清理对象池（用于在Unity主线程上清理）
        /// </summary>
        public void Clear()
        {
            _pool2D?.Clear_Sync();
            _pool3D?.Clear_Sync();

            // 清理2D根节点
            if (_pool2DRoot != null && _pool2DRoot.gameObject != null)
            {
                UnityEngine.Object.Destroy(_pool2DRoot.gameObject);
                _pool2DRoot = null;
            }

            // 清理3D根节点
            if (_pool3DRoot != null && _pool3DRoot.gameObject != null)
            {
                UnityEngine.Object.Destroy(_pool3DRoot.gameObject);
                _pool3DRoot = null;
            }
        }

        public override void Dispose()
        {
            // 注意：Dispose 可能在非主线程调用，所以不在这里清理Unity对象
            // Unity对象的清理应该在AudioManagerEntity的OnDestroy中调用Clear()方法
            base.Dispose();

            // 只清空引用，实际的Unity对象清理在OnDestroy中处理
            _pool2D = null;
            _pool3D = null;
            _pool2DRoot = null;
            _pool3DRoot = null;
        }
    }
}
